<template>
  <div class="user-profile-info-div">
    <el-row class="content">
      <el-card style="width: 100%;">
        <template #header>
          <div>
            <h3>个人资料</h3>
          </div>
        </template>
        <el-form label-width="100px">
          <div style="display: flex;
    justify-content: space-between;">
            <img :src="userInfo.avatarUrl" style="line-height: 1.42857143;
                background-color: #fff;
                border: 1px solid #ddd;
                border-radius: 4px;
                height: 130px;
                width: 130px;padding: 4px;">
            <div>
              <div class="flex-space-between">
                <el-form-item label="姓">
                  <div style="display: flex;
    flex-wrap: nowrap;">
                    <el-select v-model="userInfo.prefix" class="w-30-percent">
                      <el-option
                          v-for="item in prefixOptions"
                          :key="item.value"
                          :label="item.label"
                          :value="item.value"
                      />
                    </el-select>
                    <el-input :placeholder="$t('loc.lastName')" v-model="userInfo.lastName" type="text"
                              autocomplete="off"/>
                  </div>
                </el-form-item>
              </div>
              <el-form-item prop="lastName" class="first-name-item w-full" label="名">
                <el-input v-model="userInfo.firstName" placeholder="Please input"/>
              </el-form-item>
              <el-form-item prop="lastName" class="first-name-item w-full" label="邮箱">
                <el-input v-model="userInfo.email" placeholder="未填写"/>
              </el-form-item>
              <el-form-item prop="lastName" class="first-name-item w-full" label="手机号码">
                <el-input v-model="userInfo.phoneNumber" placeholder="未填写"/>
              </el-form-item>
              <el-form-item prop="lastName" class="first-name-item w-full" label="角色">
                <el-input v-model="role" disabled placeholder="Please input"/>
              </el-form-item>
            </div>

          </div>
        </el-form>

        <div style="display: flex;
    flex-direction: row-reverse;">
          <el-button type="primary" @click="saveUserProfileHandler" :loading="updateProfileLoading">
            {{ $t('loc.save') }}
          </el-button>
        </div>
      </el-card>
    </el-row>
    <el-row class="content">
      <el-card style="width: 100%;">
        <template #header>
          <div>
            <h3>重置密码</h3>
          </div>
        </template>
        <el-form ref="ResetPasswordRef"
                 :rules="rules"
                 label-width="100px" label-position="right" :model="resetPassword">
          <el-form-item prop="password" class="first-name-item w-full" label="当前密码">
            <el-input v-model="resetPassword.password" placeholder="当前密码" type="password"/>
          </el-form-item>
          <el-form-item prop="newPassword" class="first-name-item w-full" label="新密码">
            <el-input v-model="resetPassword.newPassword" placeholder="新密码" type="password"/>
          </el-form-item>
          <el-form-item prop="confirmPassword" class="first-name-item w-full" label="确认密码">
            <el-input v-model="resetPassword.confirmPassword" show-password placeholder="确认密码" type="password"/>
          </el-form-item>
        </el-form>
        <div style="display: flex;
              flex-direction: row-reverse;">
          <el-button type="primary" @click="savePasswordHandler" :loading="resetPasswording">
            {{ $t('loc.submit') }}
          </el-button>
        </div>
      </el-card>
    </el-row>
  </div>

</template>

<script>
import {useStore} from "vuex";
import tools from "@/utils/tools";
import UserApi from "@/api/user.js";
import {ElNotification} from "element-plus";
import {getCurrentUser, setCurrentUser} from "@/utils/common";
import {validatePsdReg} from "@/utils/rules";
import {toSignOut} from "@/utils/autoSignOut";
import { ElMessageBox } from 'element-plus'
export default {
  name: "userProfile",
  data() {
    let passwordValidator = (rule, value, callback) => {
      if (!validatePsdReg(value)) {
        callback(new Error(this.$t('loc.pwdShould8To20Char')));
      } else {
        if (this.resetPassword.confirmPassword && this.resetPassword.confirmPassword !== '') {
          this.$refs['ResetPasswordRef'].validateField('confirmPassword');
        }
        callback();
      }
    };
    let confirmPasswordValidator = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'));
      } else if (value !== this.resetPassword.newPassword) {
        callback(new Error('两次输入密码不一致!'));
      } else {
        callback();
      }
    };
    return {
      updateProfileLoading: false,
      resetPasswording: false,
      userInfo: {},
      prefixOptions: [
        {
          value: '',
          label: this.$t('loc.noPrefix'),
        },
        {
          value: 'Mr',
          label: this.$t('loc.Mr'),
        },
        {
          value: 'Miss',
          label: this.$t('loc.Miss'),
        },
      ],
      resetPassword: {
        password: '',
        newPassword: '',     // 密码
        confirmPassword: '', // 确认密码
      },
      role: '',
      rules: {
        password: [
          {required: true},
        ],
        newPassword: [
          {required: true, validator: passwordValidator},
        ],
        confirmPassword: [
          {required: true, validator: confirmPasswordValidator},
        ],
      },
    }
  },
  computed: {
    currentUser() {
      return useStore().state.user.currentUser
    },
  },
  created() {
    this.init()
  },
  methods: {
    init() {
      UserApi.getUserProfile().then(res => {
        this.userInfo = res
        let prefix = this.userInfo.displayName.split(' ')[0]
        if (prefix === this.userInfo.lastName) {
          prefix = ''
        }
        this.userInfo.prefix = prefix
        this.role = this.formatRole(this.userInfo.role)
        this.restLocalUser()
      }).catch(error => {
        this.$message.error(error.response.data.description)
      }).finally(() => {
      })
    },
    restLocalUser () {
      let user = getCurrentUser()
      user.displayName = this.userInfo.displayName
      user.lastName = this.userInfo.lastName
      user.prefix = this.userInfo.prefix
      user.email = this.userInfo.email
      user.phoneNumber = this.userInfo.phoneNumber
      setCurrentUser(user)
    },
    // 格式化角色显示
    formatRole(role) {
      return tools.formatRole(role)
    },
    savePasswordHandler () {
      this.$refs.ResetPasswordRef.validate((valid) => {
        if (valid) {
          this.resetPasswording = true
          let param = {
            userId: this.userInfo.userId,
            oldPassword: this.resetPassword.password,
            newPassword:this.resetPassword.newPassword,
          }
          $axios.patch($api.urls().updatePassword, param).then(res => {
            ElMessageBox.alert('密码更新成功，请重新登录', '', {
              confirmButtonText: 'OK',
              callback: () => {
                toSignOut()
              },
            })
          }).catch(error => {
            this.$message.error(error.response.data.description)
          }).finally(()=>{
            this.resetPasswording = false
          })
        }
      });
    },
    saveUserProfileHandler() {
      // 收集数据
      let userData = {
        id: this.userInfo.userId,
        prefix: this.userInfo.prefix,
        firstName: this.userInfo.firstName,
        lastName: this.userInfo.lastName,
        phoneNumber: this.userInfo.phoneNumber,
        email: this.userInfo.email,
      }
      if (!this.userInfo.firstName || !this.userInfo.firstName) {
        this.$message.error("请填写姓名")
      }
      this.updateProfileLoading = true
      UserApi.updateUserProfile(userData).then(res => {
        ElNotification({
          title: this.$t('loc.tip'),
          message: this.$t('loc.proFileUpdateOK'),
          position: 'bottom-right',
        })
        this.init()
      }).catch(error => {
        this.$message.error(error.response.data.description)
      }).finally(() => {
        this.updateProfileLoading = false
      })
    }
  }
}
</script>

<style scoped lang="less">
.user-profile-info-div /deep/ {
  font-size: 16px;
  color: #333333;

  .el-form-item__label {
    line-height: 15px;
    margin-bottom: 0;
    font-weight: 700;
  }

  .el-form-item {
    margin-bottom: 31px;
  }
}

.content {
  margin: 10px auto;
  background-color: #fff;
  width: 900px;
  padding: 20px;
}
</style>